package ${domain}.module.wsys.mgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.auth.Token;
import ${domain}.frame.utils.IDgenerator;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.Message;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.RoleRes;
import ${domain}.module.wsys.mpr.RoleResMapper;
import ${domain}.module.wsys.req.RoleResCheckRequest;
import ${domain}.module.wsys.req.RoleResCreateRequest;
import ${domain}.module.wsys.req.RoleResDeleteRequest;
import ${domain}.module.wsys.req.RoleResFindRequest;
import ${domain}.module.wsys.req.RoleResUpdateRequest;
import ${domain}.module.wsys.rsp.RoleResCheckResponse;
import ${domain}.module.wsys.rsp.RoleResCreateResponse;
import ${domain}.module.wsys.rsp.RoleResDeleteResponse;
import ${domain}.module.wsys.rsp.RoleResFindResponse;
import ${domain}.module.wsys.rsp.RoleResUpdateResponse;

/**
 * ROLE_RES - 角色资源关系
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
@Transactional
@Service
public class RoleResManagerImpl implements RoleResManager {

    @Autowired
    private RoleResMapper roleResMapper;

    /**
     * 插入
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public RoleResCreateResponse create(RoleResCreateRequest request, Token token) {
        RoleResCreateResponse response = new RoleResCreateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long id = IDgenerator.nextId();
        RoleRes entity = MapperUtil.map(request, RoleRes.class);
        entity.setId(id);

        long result = roleResMapper.insert(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.CREATE_FAILURE);
            return response;
        }
        response.setId(id);

        return response;
    }

    /**
     * 逻辑删除
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public RoleResDeleteResponse delete(RoleResDeleteRequest request, Token token) {
        RoleResDeleteResponse response = new RoleResDeleteResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = roleResMapper.delete(request.getId(), token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.DELETE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 更新
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public RoleResUpdateResponse update(RoleResUpdateRequest request, Token token) {
        RoleResUpdateResponse response = new RoleResUpdateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        RoleRes entity = roleResMapper.getById(request.getId(), token);
        if (entity == null) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
            return response;
        }

        MapperUtil.map(request, entity);
        long result = roleResMapper.update(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 查询
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public RoleResFindResponse find(RoleResFindRequest request, Token token) {
        RoleResFindResponse response = new RoleResFindResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getPageSize() != 0) {
            PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        }
        if (StringUtil.isNotEmpty(request.getSortKey())) {
            PageHelper.orderBy(request.getSortKey() + " " + request.getSortType());
        }
        PageInfo<RoleRes> pageInfo = new PageInfo<>(roleResMapper.find(request, token));

        response.setResult(pageInfo.getList());
        response.setTotalCount(pageInfo.getTotal());

        return response;
    }

    /**
     * 选中或取消资源
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public synchronized RoleResCheckResponse check(RoleResCheckRequest request, Token token) {
        RoleResCheckResponse response = new RoleResCheckResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        RoleResFindRequest roleResFindRequest = new RoleResFindRequest();
        roleResFindRequest.setRoleId(request.getRoleId());
        roleResFindRequest.setResId(request.getResId());
        RoleResFindResponse roleResFindResponse = this.find(roleResFindRequest, token);
        if (roleResFindResponse.hasError()) {
            response.addErrors(roleResFindResponse.getErrors());
            return response;
        }

        if (request.getChecked() && roleResFindResponse.getResult().size() == 0) {
            RoleResCreateRequest roleResCreateRequest = new RoleResCreateRequest();
            roleResCreateRequest.setRoleId(request.getRoleId());
            roleResCreateRequest.setRoleCode(request.getRoleCode());
            roleResCreateRequest.setResId(request.getResId());
            roleResCreateRequest.setResCode(request.getResCode());
            RoleResCreateResponse roleResCreateResponse = this.create(roleResCreateRequest, token);
            if (roleResCreateResponse.hasError()) {
                response.addErrors(roleResCreateResponse.getErrors());
                return response;
            }
        } else if (!request.getChecked() && roleResFindResponse.getResult().size() > 0) {
            for (RoleRes roleRes : roleResFindResponse.getResult()) {
                RoleResDeleteRequest roleResDeleteRequest = new RoleResDeleteRequest();
                roleResDeleteRequest.setId(roleRes.getId());
                RoleResDeleteResponse roleResDeleteResponse = this.delete(roleResDeleteRequest, token);
                if (roleResDeleteResponse.hasError()) {
                    response.addErrors(roleResDeleteResponse.getErrors());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return response;
                }
            }
        }

        return response;
    }
}
